package com.ug.common.ratelimit;

import com.ug.common.ratelimit.implementation.GuavaRateLimiter;
import com.ug.common.ratelimit.implementation.RedisRateLimiter;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @Author LY
 * @create 2024/8/6 15:05
 * @Description 限流切面处理
 */
@Aspect
@Component
@ConditionalOnExpression("'${admin.ratelimit.enable}' == 'true'")
@RequiredArgsConstructor
public class RateLimiterAspect {

    private static final Logger logger = LoggerFactory.getLogger(RateLimiterAspect.class);

    private final RedisRateLimiter redisRateLimiter;
    private final GuavaRateLimiter guavaRateLimiter;

    @Before("@annotation(rateLimiter)")
    public void doBefore(JoinPoint point, RateLimit rateLimiter) {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        logger.info("当前限流方法:{}", method.toGenericString());
        switch (rateLimiter.rateType()) {
            case REDIS -> redisRateLimiter.check(rateLimiter);
            case GUAVA -> guavaRateLimiter.check(rateLimiter);
            default -> redisRateLimiter.check(rateLimiter);
        }
    }
}
